<?php
/**
 * Created by PhpStorm.
 * User: Xgh
 * Date: 2021/1/7
 * Time: 15:30
 * csv导入数据，并且可兼容大文件处理
 */

namespace removeData\engine;


use removeData\lib\Rconfig;
use think\Exception;

class Csv
{
    protected $file ;

    /**
     * 获取文件总行数
     * @return int
     * @throws Exception
     */
    public function count(){
        $this->open();
        $line = 0;

        while(feof($this->file)){
            $line++;
        }
        fclose($this->file);//关闭文件
        return $line;
    }


    public function getLines($page){
        $this->loadConfig();//测试使用
        $this->open();
        //固定先获取第一行
        fseek($this->file,0);
        $fields = fgetcsv($this->file);

        if(empty($fields))
            throw new Exception('Please set the first line field');

        //过滤空字段
        $fields = array_filter($fields,function($var){
            if(empty($var)){
                return false;
            }
            return true;
        });


        $i = $j= 0;
        while($j >= $page * Rconfig::$config['limit']){
            fseek($this->file);
        }

        while($i <= Rconfig::$config['limit']){
            $line = fgetcsv($this->file);
            if(!empty($line)){
                $result = [];

                foreach($fields as $key=>$value){
                    $result[$value] = $line[$key];
                }

                yield $result;

            }

           // yield fgetcsv($this->file);
            $i++;
        }

        fclose($this->file);
    }

    //打开文件
    protected function open(){
        if(!empty($this->file))
            return $this->file;

        $file_path = Rconfig::$config['csv_ini']['file_path'];
        if(empty($file_path))
            throw new Exception('file config path is null');

        if(empty(file_exists($file_path)))
            throw new Exception('file path is not exist ');
        $this->file = $file = fopen($file_path,'r');


    }

    //生产数据
    public function createData($page){
        $i = $j= 0;

        while($j >= $page * Rconfig::$config['limit']){
            fseek($this->file);
        }

        while($i >= Rconfig::$config['limit']){
            yield fgetcsv($this->file);
            $i++;
        }
    }

    public function loadConfig(){
        Rconfig::$config = require(dirname(__DIR__) . '/config.php');
    }
}